package com.zy.smartdb.controller;

import com.zy.smartdb.enums.Action;
import com.zy.smartdb.pojo.*;
import com.zy.smartdb.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("ddl")
@Slf4j
public class DdlController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @PostMapping("/create")
    public AjaxResult create(@RequestBody CreateTableParam param) throws Exception {
        param = (CreateTableParam) StringUtil.safetyClone(param);
        String sql = buildCreateSql(param);
        jdbcTemplate.execute(sql);
        return AjaxResult.success();
    }

    @PostMapping("/alter")
    public AjaxResult alter(@RequestBody AlterTableParam param) throws Exception {
        param = (AlterTableParam) StringUtil.safetyClone(param);
        String sql = buildAlterSql(param);
        jdbcTemplate.execute(sql);
        return AjaxResult.success();
    }

    @PostMapping("/drop")
    public AjaxResult drop(@RequestBody DropTableParam param) throws Exception {
//        ids = fillSpace(ids);
//        table = fillSpace(table);
        param = (DropTableParam) StringUtil.safetyClone(param);
        String sql = buildDropSql(param);
        jdbcTemplate.execute(sql);
        return AjaxResult.success();
    }

    private String buildDropSql(DropTableParam param) {
        String sql = "drop table {0}";
        sql = sql.replace("{0}", param.getTable());
        return sql;
    }

    private String buildAlterSql(AlterTableParam param) {
//        String sql = "ALTER TABLE `smart-db`.`user` ADD COLUMN `comment`varchar(255) NOT NULL AFTER `age`";
        String sql = "ALTER TABLE {0} {1}";
        StringBuilder sb = new StringBuilder();
        for (ColumnAction column : param.getColumns()) {
            sb.append(column.getAction()).append(" COLUMN ").append(column.getName()).append(' ');
            if (column.getAction() == Action.DROP) {
                sb.append(',');
                continue;
            }
            sb.append(column.getType()).append(' ');
            if (column.getNotNull()) {
                sb.append("NOT NULL ");
            }
            sb.append("after ").append(column.getAfter()).append(',');
        }
        String columns = sb.substring(0, sb.length() - 1);
        sql = sql.replace("{0}", param.getTable())
                .replace("{1}", columns);
        return sql;
    }

    private String buildCreateSql(CreateTableParam param) {
        String sql = "CREATE TABLE {0} ({1})";
//                "  `id` int NOT NULL AUTO_INCREMENT,\n" +
//                "  `username` varchar(255) NOT NULL,\n" +
//                "  `age` int DEFAULT NULL,\n" +
//                "  PRIMARY KEY (`id`)\n" +
//                ")";

        StringBuilder sb = new StringBuilder();
        for (ColumnInfo columnInfo : param.getColumns()) {
            sb.append(columnInfo.getName()).append(' ').append(columnInfo.getType()).append(' ');
            if (columnInfo.getNotNull()) {
                sb.append("not null ");
            }
            if (!StringUtil.isNullOrEmpty(columnInfo.getDefaultValue())) {
                sb.append("default ").append(columnInfo.getDefaultValue()).append(' ');
            }

            sb.append(',');
        }

        if (param.getUniqueCols().size() > 0) {
            sb.append("UNIQUE KEY ");
            for (String col : param.getUniqueCols()) {
                sb.append(col).append('_');
            }

            sb.delete(sb.length() - 1, sb.length());
            sb.append(' ');
            sb.append(('('));
            for (String col : param.getUniqueCols()) {
                sb.append(col).append(',');
            }
            sb.delete(sb.length() - 1, sb.length());
            sb.append((") USING BTREE "));

        }
        String columns = sb.substring(0, sb.length() - 1);
        sql = sql.replace("{0}", param.getTable())
                .replace("{1}", columns);
        return sql;
    }
}
